package cn.smbms.controller;

import cn.smbms.service.RoleService;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.pojo.vo.UserListVO;
import cn.smbms.service.UserService;
import cn.smbms.util.PageBean;
import com.alibaba.fastjson.JSON;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author Tequila
 **/
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    /**
     * produces = "application/json;charset=utf-8"  随处使用灵活处理
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findUserById")
    public String findUserById(@RequestParam Integer id){
        User user = userService.findUser(id);
        return  JSON.toJSONString(user);


    }

    @ResponseBody // 之前的返回值是请求转发 打上此注解之后  返回值变成异步请求数据  AJAX
    @RequestMapping("/userCodeIsExists")
    public String userCodeIsExists(@RequestParam String userCode){
        User user = userService.login(userCode, null);
        Map<String,Object> map = new HashMap<>();

        if (user != null){
            map.put("userCode","exist");
        }else{
            map.put("userCode","noexist");
        }
        return JSON.toJSONString(map);

    }



    @RequestMapping("/useraddsave")
    public String addUser(HttpServletRequest request,@ModelAttribute User user, @RequestParam(value = "attchs",required = false) MultipartFile multipartFile){
        String idPicPath = "";
        if (multipartFile != null){
            // 开启文件上传操作
            // 1.定义上传路径    获取上下文的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"fileUpload");
            // 2.获取原文件名
            String filename = multipartFile.getOriginalFilename();
            // 3.获取文件大小
            long size = multipartFile.getSize();
            // 4.获取后缀
            String extension = FilenameUtils.getExtension(filename);
            List<String> list = Arrays.asList("jpg","png","jpeg");
            if (!list.contains(extension.toLowerCase())){ // toLowerCase 将字符串全部变成小写
                request.setAttribute("idPicPathError","对不起,暂时只支持,jpg,png,jpeg 类型的图片");
                return "useradd";
            }else if (size > 10485760){
                request.setAttribute("idPicPathError","文件超出上传大小");
                return "useradd";
            }else{
                // 当前系统时间戳  +  随机数  + _Personal.jpg  -> uuid
                String newFileName = UUID.randomUUID()+"_Personal."+extension;
                // 核心功能 开始文件上传
                File file = new File(filePath,newFileName);
                if (!file.exists()){
                    file.mkdirs();// 创建目录
                }
                try {
                    multipartFile.transferTo(file);  // 核心上传功能
                    // 保存上传地址  "statics/fileUpload/newFileName"  相对地址
                    idPicPath = "statics"+File.separator+"fileUpload"+File.separator+newFileName;
                    user.setIdPicPath(idPicPath);
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("idPicPathError","文件上传异常,请重试!");
                }
            }
        }
        User userSession = (User) request.getSession().getAttribute("userSession");
        user.setCreatedBy(userSession.getId());
        user.setCreationDate(new Date());

        //保存用户信息
        boolean result = userService.addUser(user);
        if (result){
            return "redirect:/user/userlist";
        }
        return "useradd";

    }

    @RequestMapping("/touseradd")
    public String toUserAdd(){
        return "useradd";
    }

    /**
     * /delete/"+obj.attr("userid")
     * @param
     * @return
     */
    @RequestMapping("/delete/{id}")
    public String deleteUser(@PathVariable Integer id){
        userService.deleteUser(id);
        return "redirect:/user/userlist";
    }
    @RequestMapping("/modifyUser")
    public String updateUser(@ModelAttribute User user){
       boolean result =  userService.updateUser(user);
       if (result){
           return "redirect:/user/userlist";
       }
       return "redirect:/user/toModify/"+user.getId();
    }

    /**
     * /toModify/"+ obj.attr("userid");
     * 修改用户
     */
    @RequestMapping("/toModify/{id}")
    public String toUpdateUser(@PathVariable Integer id,HttpServletRequest request){
        User user =  userService.findUser(id);
        request.setAttribute("user",user);
        return "usermodify";
    }


    /*/view/"+ obj.attr("userid");*/
    /**
     * {id}:接收路径上的参数
     * @PathVariable : 接收路径上的变量
     * @return
     */
    @RequestMapping("/view/{id}")
    public String finUser(@PathVariable Integer id,HttpServletRequest request){
       User user =  userService.findUser(id);
       request.setAttribute("user",user);
       return "userview";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("userSession");
        return "login";

    }
    @RequestMapping("/userlist")
    public String findUserList(@ModelAttribute UserListVO vo, HttpServletRequest request){
        if(vo.getPageIndex() == null){
            vo.setPageIndex(1);
        }
        vo.setPageSize(5);
        // VO 就是用来传递参数的对象 以后会经常使用
        PageBean<User> page = userService.findPage(vo);
        request.setAttribute("page",page);
        // 查询角色列表
        List<Role> roleList = roleService.findRoleList();
        request.setAttribute("roleList",roleList);
        //回显
        request.setAttribute("queryUserName",vo.getQueryName());
        request.setAttribute("queryUserRole",vo.getQueryUserRole());
        return "userlist";

    }

    @RequestMapping("/dologin")
    public String doLogin(){
        return "login";
    }
    @RequestMapping("/main")
    public String main() throws RuntimeException {
        /*try {
            int i = 1/0;
        } catch (Exception e) {
            throw new RuntimeException();
        }*/
        /*判断用户是否为空 改为使用拦截器 拦截所有的请求   以后所有的请求都是在登陆之后完成*/
        return "frame";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, @RequestParam String userCode, @RequestParam String userPassword){
        if (userCode == null && userPassword == null){
            request.setAttribute("error","用户名密码不能为空!");
            return "login";
        }

        User user = userService.login(userCode,userPassword);
        if (user != null){
            request.getSession().setAttribute("userSession",user);
            return "redirect:/user/main";
        }else{
            request.setAttribute("error","用户名或者密码错误!");
            return "login";
        }

    }
}
